home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pkgutil.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  19KB  |  645 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Utilities to support packages.'''
  5. import os
  6. import sys
  7. import imp
  8. import os.path as os
  9. from types import ModuleType
  10. __all__ = [
  11.     'get_importer',
  12.     'iter_importers',
  13.     'get_loader',
  14.     'find_loader',
  15.     'walk_packages',
  16.     'iter_modules',
  17.     'ImpImporter',
  18.     'ImpLoader',
  19.     'read_code',
  20.     'extend_path']
  21.  
  22. def read_code(stream):
  23.     import marshal as marshal
  24.     magic = stream.read(4)
  25.     if magic != imp.get_magic():
  26.         return None
  27.     stream.read(4)
  28.     return marshal.load(stream)
  29.  
  30.  
  31. def simplegeneric(func):
  32.     '''Make a trivial single-dispatch generic function'''
  33.     registry = { }
  34.     
  35.     def wrapper(*args, **kw):
  36.         ob = args[0]
  37.         
  38.         try:
  39.             cls = ob.__class__
  40.         except AttributeError:
  41.             cls = type(ob)
  42.  
  43.         
  44.         try:
  45.             mro = cls.__mro__
  46.         except AttributeError:
  47.             
  48.             try:
  49.                 
  50.                 class cls(cls, object):
  51.                     pass
  52.  
  53.                 mro = cls.__mro__[1:]
  54.             except TypeError:
  55.                 mro = (object,)
  56.             except:
  57.                 None<EXCEPTION MATCH>TypeError
  58.             
  59.  
  60.             None<EXCEPTION MATCH>TypeError
  61.  
  62.         for t in mro:
  63.             if t in registry:
  64.                 return registry[t](*args, **kw)
  65.         else:
  66.             return func(*args, **kw)
  67.         return t in registry
  68.  
  69.     
  70.     try:
  71.         wrapper.__name__ = func.__name__
  72.     except (TypeError, AttributeError):
  73.         (None, None)
  74.         (None, None)
  75.     except:
  76.         (None, None)
  77.  
  78.     
  79.     def register(typ, func = ((None, None), None)):
  80.         if func is None:
  81.             return (lambda f: register(typ, f))
  82.         registry[typ] = func
  83.         return func
  84.  
  85.     wrapper.__dict__ = func.__dict__
  86.     wrapper.__doc__ = func.__doc__
  87.     wrapper.register = register
  88.     return wrapper
  89.  
  90.  
  91. def walk_packages(path = None, prefix = '', onerror = None):
  92.     """Yields (module_loader, name, ispkg) for all modules recursively
  93.     on path, or, if path is None, all accessible modules.
  94.  
  95.     'path' should be either None or a list of paths to look for
  96.     modules in.
  97.  
  98.     'prefix' is a string to output on the front of every module name
  99.     on output.
  100.  
  101.     Note that this function must import all *packages* (NOT all
  102.     modules!) on the given path, in order to access the __path__
  103.     attribute to find submodules.
  104.  
  105.     'onerror' is a function which gets called with one argument (the
  106.     name of the package which was being imported) if any exception
  107.     occurs while trying to import a package.  If no onerror function is
  108.     supplied, ImportErrors are caught and ignored, while all other
  109.     exceptions are propagated, terminating the search.
  110.  
  111.     Examples:
  112.  
  113.     # list all modules python can access
  114.     walk_packages()
  115.  
  116.     # list all submodules of ctypes
  117.     walk_packages(ctypes.__path__, ctypes.__name__+'.')
  118.     """
  119.     
  120.     def seen(p, m = { }):
  121.         if p in m:
  122.             return True
  123.         m[p] = True
  124.  
  125.     for importer, name, ispkg in iter_modules(path, prefix):
  126.         yield (importer, name, ispkg)
  127.         if ispkg:
  128.             
  129.             try:
  130.                 __import__(name)
  131.             except ImportError:
  132.                 if onerror is not None:
  133.                     onerror(name)
  134.                 
  135.             except Exception:
  136.                 if onerror is not None:
  137.                     onerror(name)
  138.                 else:
  139.                     raise 
  140.                 onerror is not None
  141.  
  142.             if not getattr(sys.modules[name], '__path__', None):
  143.                 pass
  144.             path = []
  145.             path = _[1]
  146.             for item in walk_packages(path, name + '.', onerror):
  147.                 yield item
  148.                 []
  149.             
  150.         []
  151.     
  152.  
  153.  
  154. def iter_modules(path = None, prefix = ''):
  155.     """Yields (module_loader, name, ispkg) for all submodules on path,
  156.     or, if path is None, all top-level modules on sys.path.
  157.  
  158.     'path' should be either None or a list of paths to look for
  159.     modules in.
  160.  
  161.     'prefix' is a string to output on the front of every module name
  162.     on output.
  163.     """
  164.     if path is None:
  165.         importers = iter_importers()
  166.     else:
  167.         importers = map(get_importer, path)
  168.     yielded = { }
  169.     for i in importers:
  170.         for name, ispkg in iter_importer_modules(i, prefix):
  171.             if name not in yielded:
  172.                 yielded[name] = 1
  173.                 yield (i, name, ispkg)
  174.                 continue
  175.         
  176.     
  177.  
  178.  
  179. def iter_importer_modules(importer, prefix = ''):
  180.     if not hasattr(importer, 'iter_modules'):
  181.         return []
  182.     return importer.iter_modules(prefix)
  183.  
  184. iter_importer_modules = simplegeneric(iter_importer_modules)
  185.  
  186. class ImpImporter:
  187.     '''PEP 302 Importer that wraps Python\'s "classic" import algorithm
  188.  
  189.     ImpImporter(dirname) produces a PEP 302 importer that searches that
  190.     directory.  ImpImporter(None) produces a PEP 302 importer that searches
  191.     the current sys.path, plus any modules that are frozen or built-in.
  192.  
  193.     Note that ImpImporter does not currently support being used by placement
  194.     on sys.meta_path.
  195.     '''
  196.     
  197.     def __init__(self, path = None):
  198.         self.path = path
  199.  
  200.     
  201.     def find_module(self, fullname, path = None):
  202.         subname = fullname.split('.')[-1]
  203.         if subname != fullname and self.path is None:
  204.             return None
  205.         if self.path is None:
  206.             path = None
  207.         else:
  208.             path = [
  209.                 os.path.realpath(self.path)]
  210.         
  211.         try:
  212.             (file, filename, etc) = imp.find_module(subname, path)
  213.         except ImportError:
  214.             return None
  215.  
  216.         return ImpLoader(fullname, file, filename, etc)
  217.  
  218.     
  219.     def iter_modules(self, prefix = ''):
  220.         if self.path is None or not os.path.isdir(self.path):
  221.             return None
  222.         yielded = { }
  223.         import inspect as inspect
  224.         filenames = os.listdir(self.path)
  225.         filenames.sort()
  226.         for fn in filenames:
  227.             modname = inspect.getmodulename(fn)
  228.             if modname == '__init__' or modname in yielded:
  229.                 continue
  230.             
  231.             path = os.path.join(self.path, fn)
  232.             ispkg = False
  233.             if not modname and os.path.isdir(path) and '.' not in fn:
  234.                 modname = fn
  235.                 for fn in os.listdir(path):
  236.                     subname = inspect.getmodulename(fn)
  237.                     if subname == '__init__':
  238.                         ispkg = True
  239.                         break
  240.                         continue
  241.                 
  242.             
  243.             if modname and '.' not in modname:
  244.                 yielded[modname] = 1
  245.                 yield (prefix + modname, ispkg)
  246.                 continue
  247.         
  248.  
  249.  
  250.  
  251. class ImpLoader:
  252.     '''PEP 302 Loader that wraps Python\'s "classic" import algorithm
  253.     '''
  254.     code = None
  255.     source = None
  256.     
  257.     def __init__(self, fullname, file, filename, etc):
  258.         self.file = file
  259.         self.filename = filename
  260.         self.fullname = fullname
  261.         self.etc = etc
  262.  
  263.     
  264.     def load_module(self, fullname):
  265.         self._reopen()
  266.         
  267.         try:
  268.             mod = imp.load_module(fullname, self.file, self.filename, self.etc)
  269.         finally:
  270.             if self.file:
  271.                 self.file.close()
  272.             
  273.  
  274.         return mod
  275.  
  276.     
  277.     def get_data(self, pathname):
  278.         return open(pathname, 'rb').read()
  279.  
  280.     
  281.     def _reopen(self):
  282.         if self.file and self.file.closed:
  283.             mod_type = self.etc[2]
  284.             if mod_type == imp.PY_SOURCE:
  285.                 self.file = open(self.filename, 'rU')
  286.             elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION):
  287.                 self.file = open(self.filename, 'rb')
  288.             
  289.         
  290.  
  291.     
  292.     def _fix_name(self, fullname):
  293.         if fullname is None:
  294.             fullname = self.fullname
  295.         elif fullname != self.fullname:
  296.             raise ImportError('Loader for module %s cannot handle module %s' % (self.fullname, fullname))
  297.         
  298.         return fullname
  299.  
  300.     
  301.     def is_package(self, fullname):
  302.         fullname = self._fix_name(fullname)
  303.         return self.etc[2] == imp.PKG_DIRECTORY
  304.  
  305.     
  306.     def get_code(self, fullname = None):
  307.         fullname = self._fix_name(fullname)
  308.         if self.code is None:
  309.             mod_type = self.etc[2]
  310.             if mod_type == imp.PY_SOURCE:
  311.                 source = self.get_source(fullname)
  312.                 self.code = compile(source, self.filename, 'exec')
  313.             elif mod_type == imp.PY_COMPILED:
  314.                 self._reopen()
  315.                 
  316.                 try:
  317.                     self.code = read_code(self.file)
  318.                 finally:
  319.                     self.file.close()
  320.  
  321.             elif mod_type == imp.PKG_DIRECTORY:
  322.                 self.code = self._get_delegate().get_code()
  323.             
  324.         
  325.         return self.code
  326.  
  327.     
  328.     def get_source(self, fullname = None):
  329.         fullname = self._fix_name(fullname)
  330.         if self.source is None:
  331.             mod_type = self.etc[2]
  332.             if mod_type == imp.PY_SOURCE:
  333.                 self._reopen()
  334.                 
  335.                 try:
  336.                     self.source = self.file.read()
  337.                 finally:
  338.                     self.file.close()
  339.  
  340.             elif mod_type == imp.PY_COMPILED:
  341.                 if os.path.exists(self.filename[:-1]):
  342.                     f = open(self.filename[:-1], 'rU')
  343.                     self.source = f.read()
  344.                     f.close()
  345.                 
  346.             elif mod_type == imp.PKG_DIRECTORY:
  347.                 self.source = self._get_delegate().get_source()
  348.             
  349.         
  350.         return self.source
  351.  
  352.     
  353.     def _get_delegate(self):
  354.         return ImpImporter(self.filename).find_module('__init__')
  355.  
  356.     
  357.     def get_filename(self, fullname = None):
  358.         fullname = self._fix_name(fullname)
  359.         mod_type = self.etc[2]
  360.         if self.etc[2] == imp.PKG_DIRECTORY:
  361.             return self._get_delegate().get_filename()
  362.         if self.etc[2] in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION):
  363.             return self.filename
  364.  
  365.  
  366.  
  367. try:
  368.     import zipimport
  369.     from zipimport import zipimporter
  370.     
  371.     def iter_zipimport_modules(importer, prefix = ''):
  372.         dirlist = zipimport._zip_directory_cache[importer.archive].keys()
  373.         dirlist.sort()
  374.         _prefix = importer.prefix
  375.         plen = len(_prefix)
  376.         yielded = { }
  377.         import inspect
  378.         for fn in dirlist:
  379.             if not fn.startswith(_prefix):
  380.                 continue
  381.             
  382.             fn = fn[plen:].split(os.sep)
  383.             if len(fn) == 2 and fn[1].startswith('__init__.py'):
  384.                 if fn[0] not in yielded:
  385.                     yielded[fn[0]] = 1
  386.                     yield (fn[0], True)
  387.                 
  388.             
  389.             if len(fn) != 1:
  390.                 continue
  391.             
  392.             modname = inspect.getmodulename(fn[0])
  393.             if modname == '__init__':
  394.                 continue
  395.             
  396.             if modname and '.' not in modname and modname not in yielded:
  397.                 yielded[modname] = 1
  398.                 yield (prefix + modname, False)
  399.                 continue
  400.         
  401.  
  402.     iter_importer_modules.register(zipimporter, iter_zipimport_modules)
  403. except ImportError:
  404.     pass
  405.  
  406.  
  407. def get_importer(path_item):
  408.     '''Retrieve a PEP 302 importer for the given path item
  409.  
  410.     The returned importer is cached in sys.path_importer_cache
  411.     if it was newly created by a path hook.
  412.  
  413.     If there is no importer, a wrapper around the basic import
  414.     machinery is returned. This wrapper is never inserted into
  415.     the importer cache (None is inserted instead).
  416.  
  417.     The cache (or part of it) can be cleared manually if a
  418.     rescan of sys.path_hooks is necessary.
  419.     '''
  420.     
  421.     try:
  422.         importer = sys.path_importer_cache[path_item]
  423.     except KeyError:
  424.         for path_hook in sys.path_hooks:
  425.             
  426.             try:
  427.                 importer = path_hook(path_item)
  428.             continue
  429.             except ImportError:
  430.                 continue
  431.             
  432.  
  433.         else:
  434.             importer = None
  435.         sys.path_importer_cache.setdefault(path_item, importer)
  436.     except:
  437.         None<EXCEPTION MATCH>ImportError
  438.  
  439.     if importer is None:
  440.         
  441.         try:
  442.             importer = ImpImporter(path_item)
  443.         except ImportError:
  444.             None<EXCEPTION MATCH>ImportError
  445.             None<EXCEPTION MATCH>ImportError
  446.             importer = None
  447.         except:
  448.             None<EXCEPTION MATCH>ImportError<EXCEPTION MATCH>ImportError
  449.         
  450.  
  451.     None<EXCEPTION MATCH>ImportError
  452.     return importer
  453.  
  454.  
  455. def iter_importers(fullname = ''):
  456.     '''Yield PEP 302 importers for the given module name
  457.  
  458.     If fullname contains a \'.\', the importers will be for the package
  459.     containing fullname, otherwise they will be importers for sys.meta_path,
  460.     sys.path, and Python\'s "classic" import machinery, in that order.  If
  461.     the named module is in a package, that package is imported as a side
  462.     effect of invoking this function.
  463.  
  464.     Non PEP 302 mechanisms (e.g. the Windows registry) used by the
  465.     standard import machinery to find files in alternative locations
  466.     are partially supported, but are searched AFTER sys.path. Normally,
  467.     these locations are searched BEFORE sys.path, preventing sys.path
  468.     entries from shadowing them.
  469.  
  470.     For this to cause a visible difference in behaviour, there must
  471.     be a module or package name that is accessible via both sys.path
  472.     and one of the non PEP 302 file system mechanisms. In this case,
  473.     the emulation will find the former version, while the builtin
  474.     import mechanism will find the latter.
  475.  
  476.     Items of the following types can be affected by this discrepancy:
  477.         imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY
  478.     '''
  479.     if fullname.startswith('.'):
  480.         raise ImportError('Relative module names not supported')
  481.     fullname.startswith('.')
  482.     if '.' in fullname:
  483.         pkg = '.'.join(fullname.split('.')[:-1])
  484.         if pkg not in sys.modules:
  485.             __import__(pkg)
  486.         
  487.         if not getattr(sys.modules[pkg], '__path__', None):
  488.             pass
  489.         path = []
  490.     else:
  491.         for importer in sys.meta_path:
  492.             yield importer
  493.         
  494.         path = sys.path
  495.     for item in path:
  496.         yield get_importer(item)
  497.     
  498.     if '.' not in fullname:
  499.         yield ImpImporter()
  500.     
  501.  
  502.  
  503. def get_loader(module_or_name):
  504.     '''Get a PEP 302 "loader" object for module_or_name
  505.  
  506.     If the module or package is accessible via the normal import
  507.     mechanism, a wrapper around the relevant part of that machinery
  508.     is returned.  Returns None if the module cannot be found or imported.
  509.     If the named module is not already imported, its containing package
  510.     (if any) is imported, in order to establish the package __path__.
  511.  
  512.     This function uses iter_importers(), and is thus subject to the same
  513.     limitations regarding platform-specific special import locations such
  514.     as the Windows registry.
  515.     '''
  516.     if module_or_name in sys.modules:
  517.         module_or_name = sys.modules[module_or_name]
  518.     
  519.     if isinstance(module_or_name, ModuleType):
  520.         module = module_or_name
  521.         loader = getattr(module, '__loader__', None)
  522.         if loader is not None:
  523.             return loader
  524.         fullname = module.__name__
  525.     else:
  526.         fullname = module_or_name
  527.     return find_loader(fullname)
  528.  
  529.  
  530. def find_loader(fullname):
  531.     '''Find a PEP 302 "loader" object for fullname
  532.  
  533.     If fullname contains dots, path must be the containing package\'s __path__.
  534.     Returns None if the module cannot be found or imported. This function uses
  535.     iter_importers(), and is thus subject to the same limitations regarding
  536.     platform-specific special import locations such as the Windows registry.
  537.     '''
  538.     for importer in iter_importers(fullname):
  539.         loader = importer.find_module(fullname)
  540.         if loader is not None:
  541.             return loader
  542.     
  543.  
  544.  
  545. def extend_path(path, name):
  546.     """Extend a package's path.
  547.  
  548.     Intended use is to place the following code in a package's __init__.py:
  549.  
  550.         from pkgutil import extend_path
  551.         __path__ = extend_path(__path__, __name__)
  552.  
  553.     This will add to the package's __path__ all subdirectories of
  554.     directories on sys.path named after the package.  This is useful
  555.     if one wants to distribute different parts of a single logical
  556.     package as multiple directories.
  557.  
  558.     It also looks for *.pkg files beginning where * matches the name
  559.     argument.  This feature is similar to *.pth files (see site.py),
  560.     except that it doesn't special-case lines starting with 'import'.
  561.     A *.pkg file is trusted at face value: apart from checking for
  562.     duplicates, all entries found in a *.pkg file are added to the
  563.     path, regardless of whether they are exist the filesystem.  (This
  564.     is a feature.)
  565.  
  566.     If the input path is not a list (as is the case for frozen
  567.     packages) it is returned unchanged.  The input path is not
  568.     modified; an extended copy is returned.  Items are only appended
  569.     to the copy at the end.
  570.  
  571.     It is assumed that sys.path is a sequence.  Items of sys.path that
  572.     are not (unicode or 8-bit) strings referring to existing
  573.     directories are ignored.  Unicode items of sys.path that cause
  574.     errors when used as filenames may cause this function to raise an
  575.     exception (in line with os.path.isdir() behavior).
  576.     """
  577.     if not isinstance(path, list):
  578.         return path
  579.     pname = os.path.join(*name.split('.'))
  580.     sname = os.extsep.join(name.split('.'))
  581.     sname_pkg = sname + os.extsep + 'pkg'
  582.     init_py = '__init__' + os.extsep + 'py'
  583.     path = path[:]
  584.     for dir in sys.path:
  585.         if not isinstance(dir, basestring) or not os.path.isdir(dir):
  586.             continue
  587.         
  588.         subdir = os.path.join(dir, pname)
  589.         initfile = os.path.join(subdir, init_py)
  590.         if subdir not in path and os.path.isfile(initfile):
  591.             path.append(subdir)
  592.         
  593.         pkgfile = os.path.join(dir, sname_pkg)
  594.         if os.path.isfile(pkgfile):
  595.             
  596.             try:
  597.                 f = open(pkgfile)
  598.             except IOError:
  599.                 msg = None
  600.                 sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg))
  601.  
  602.             for line in f:
  603.                 line = line.rstrip('\n')
  604.                 if not line or line.startswith('#'):
  605.                     continue
  606.                 
  607.                 path.append(line)
  608.             
  609.             f.close()
  610.             continue
  611.     
  612.     return path
  613.  
  614.  
  615. def get_data(package, resource):
  616.     """Get a resource from a package.
  617.  
  618.     This is a wrapper round the PEP 302 loader get_data API. The package
  619.     argument should be the name of a package, in standard module format
  620.     (foo.bar). The resource argument should be in the form of a relative
  621.     filename, using '/' as the path separator. The parent directory name '..'
  622.     is not allowed, and nor is a rooted name (starting with a '/').
  623.  
  624.     The function returns a binary string, which is the contents of the
  625.     specified resource.
  626.  
  627.     For packages located in the filesystem, which have already been imported,
  628.     this is the rough equivalent of
  629.  
  630.         d = os.path.dirname(sys.modules[package].__file__)
  631.         data = open(os.path.join(d, resource), 'rb').read()
  632.  
  633.     If the package cannot be located or loaded, or it uses a PEP 302 loader
  634.     which does not support get_data(), then None is returned.
  635.     """
  636.     loader = get_loader(package)
  637.     mod = not hasattr(loader, 'get_data') if loader is None or not hasattr(loader, 'get_data') else loader.load_module(package)
  638.     if mod is None or not hasattr(mod, '__file__'):
  639.         return None
  640.     parts = resource.split('/')
  641.     parts.insert(0, os.path.dirname(mod.__file__))
  642.     resource_name = os.path.join(*parts)
  643.     return loader.get_data(resource_name)
  644.  
  645.